import { contextBridge, ipcRenderer } from "electron";
import { electronAPI } from "@electron-toolkit/preload";
// Custom APIs for renderer
const api = {};

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.

if (process.contextIsolated) {
	try {
		contextBridge.exposeInMainWorld("electron", electronAPI);
		contextBridge.exposeInMainWorld("api", api);
		contextBridge.exposeInMainWorld("electronAPI", {
			// 发送消息到主进程
			send: (channel, data) => {
				// 限制可使用的 channel
				const validChannels = ["get-window-size"];
				if (validChannels.includes(channel)) {
					ipcRenderer.send(channel, data);
				}
			},
			// 从主进程接收消息
			on: (channel, callback) => {
				// 限制可使用的 channel
				const validChannels = ["window-size-changed"];
				if (validChannels.includes(channel)) {
					// 创建一个包装函数，以便可以正确地移除监听器
					const subscription = (event, ...args) => callback(...args);
					ipcRenderer.on(channel, subscription);

					// 返回一个取消订阅函数
					return () => ipcRenderer.removeListener(channel, subscription);
				}
			}
		});
	} catch (error) {
		console.error(error);
	}
} else {
	// @ts-ignore (define in dts)
	window.electron = electronAPI;
	// @ts-ignore (define in dts)
	window.api = api;
}
